/**
 *
 * @author 朱雀
 */
Ext.define('SvgEditor.graph.Path', {
	extend: 'SvgEditor.graph.Model',
	init: function(canvas, modelConfig, noPlate) {
		var me = this, config = {
			start: [0, 0], end: [0, 0]
		};
		if (!modelConfig.data) {
			modelConfig.data = {modelType: 'SequenceFlow'};
		} else if (modelConfig.data && !modelConfig.data.modelType) {
			Ext.apply(modelConfig.data, {modelType: 'SequenceFlow'});
		}
		var flow = me.callParent(arguments);
		Ext.apply(flow, config);
		if (!noPlate) {
			var path = flow.attrs.path, len = path.length, flowPlate = flow.clone().
					attr({'arrow-end': '', 'stroke-width': 16, stroke: 'white'}).toBack()
			flow.flowPlate = flowPlate;
			flowPlate.flow = flow;
			flowPlate.start = flow.start = [path[0][1], path[0][2]];
			flowPlate.end = flow.end = [path[len - 1][1], path[len - 1][2]];
			if (!canvas.readOnly) {
				flowPlate.drag(me.onPlateMove, me.onDDStart, me.onPlateEnd);
			}
		}
		return flow;
	},
	onDDStart: function(x, y, e) {
		var flow = this;
		if (flow.flow) {
			flow = flow.flow;
		}
		if (!(flow.flowFrom || flow.flowTo))
			flow.oldPath = Ext.decode(Ext.encode(flow.attrs.path));
	},
	onDDMove: function(dx, dy, x, y, e) {
		var flow = this;
		if (!(flow.flowFrom || flow.flowTo)) {
			var path = flow.attrs.path;
			for (var i = 0; i < path.length; i++) {
				path[i][1] = this.oldPath[i][1] + dx;
				path[i][2] = this.oldPath[i][2] + dy;
			}
			flow.attr({path: path});
			if (flow.flowPlate) {
				flow.flowPlate.attr({path: path});
			}
		}
	},
	onDDEnd: function(x, y, e) {
		var flow = this;
		if (!(flow.flowFrom || flow.flowTo)) {
			var flowPlate = flow.flowPlate, canvas = flow.canvas, path = flow.attrs.path;
			flow.start = [path[0][1], path[0][2]];
			flow.end = [path[path.length - 1][1], path[path.length - 1][2]];
			if (flowPlate) {
				flowPlate.start = flow.start;
				flowPlate.end = flow.end;
			}
			canvas.viewAnchor(canvas, flow);
		}
	},
	onPlateMove: function(dx, dy, x, y, e) {
		var flowPlate = this, flow = flowPlate.flow;
		if (!(flow.flowFrom || flow.flowTo)) {
			var path = [
				['M', flow.start[0] + dx, flow.start[1] + dy],
				['L', flow.end[0] + dx, flow.end[1] + dy]
			];
			flow.attr({path: path});
			flow.flowPlate.attr({path: path});
		}
	},
	onPlateEnd: function(x, y, e) {
		var flowPlate = this, flow = flowPlate.flow;
		if (!(flow.flowFrom || flow.flowTo)) {
			var canvas = flow.canvas, path = flow.attrs.path;
			flowPlate.start = flow.start = [path[0][1], path[0][2]];
			flowPlate.end = flow.end = [path[path.length - 1][1], path[path.length - 1][2]];
			canvas.viewAnchor(canvas, flow);
		}
	}
});